package com.lyn;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.Properties;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;

public class DBPoolConnection {  
	  
    private static DBPoolConnection dbPoolConnection = null;  
    private static DruidDataSource dds = null;  
    
    //加载properties文件，并使用properties文件初始化DruidDataSource
    static {  
        Properties properties = loadPropertyFile("oracle-config.properties");
        try {
        	dds = (DruidDataSource)DruidDataSourceFactory.createDataSource(properties);
        } catch(Exception e) {
        	e.printStackTrace();
        }
    }

    //单例
    private  DBPoolConnection() {
    	
    }
    
    //单例
    public static synchronized DBPoolConnection getInstance() {
    	if(dbPoolConnection==null) {
    		dbPoolConnection = new DBPoolConnection();
    	}
    	return dbPoolConnection;
    }
    
    //最终目标：获取DruidDataSource
    public DruidDataSource getDataSource() throws SQLException {
    	return dds;
    }
    
    //从DruidDataSource中获取Connection，用的少
    public DruidPooledConnection getConnection() throws SQLException {
    	return dds.getConnection();
    }
    
    //根据路径加载properties文件
    public static Properties loadPropertyFile(String fullFile) {  
        String webRootPath = null;  
        if (fullFile==null || fullFile.equals("")) {
            throw new IllegalArgumentException(  
                    "Properties file path can not be null : " + fullFile);
        }
        webRootPath = DBPoolConnection.class.getClassLoader().getResource("\\").getPath();
        webRootPath = new File(webRootPath).getParent();
        InputStream inputStream = null;
        Properties p = null;
        try {
        	String propertiesFilePath = webRootPath+File.separator+fullFile;
        	System.out.println(propertiesFilePath);
        	inputStream = new FileInputStream(new File(propertiesFilePath));
        	p = new Properties();
        	p.load(inputStream);
        } catch (FileNotFoundException e) {
			throw new IllegalArgumentException("Properties file can't be found:"+fullFile);
		} catch (IOException e) {
			throw new IllegalArgumentException("Properties file can not be loaded:"+fullFile);
		} finally {
			try {
				if(inputStream!=null) {
					inputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
        return p;
    }
}